package com.fancy.learncenter.ui.fragment;


import android.Manifest;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.fancy.learncenter.R;
import com.fancy.learncenter.bean.AudioBean;
import com.fancy.learncenter.common.Constant;
import com.fancy.learncenter.common.LoginUserSharePrefernce;
import com.fancy.learncenter.db.RecorderAudioDBManager;
import com.fancy.learncenter.net.CustomNetSubscriber;
import com.fancy.learncenter.net.HttpMehtod;
import com.fancy.learncenter.ui.activity.RecorderActivity;
import com.fancy.learncenter.ui.adapter.FragmentLoactionAudioAdapter;
import com.fancy.learncenter.ui.adapter.base.CommonRecycleViewAdapter;
import com.fancy.learncenter.ui.adapter.base.CustomViewHold;
import com.fancy.learncenter.utils.DataUtil;
import com.fancy.learncenter.utils.LogUtil;
import com.fancy.learncenter.utils.NetUtil;
import com.fancy.learncenter.utils.PermissionHelper;
import com.fancy.learncenter.utils.SPUtils;
import com.fancy.learncenter.utils.Utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.ResponseBody;
import retrofit2.Response;

/**
 * A simple {@link Fragment} subclass.
 */
public class LocationAuidoFragment extends Fragment {
    @Bind(R.id.recyclerView)
    RecyclerView recyclerView;

    private FragmentLoactionAudioAdapter listAdapter;
    private ArrayList<AudioBean> listData;

    PermissionHelper mHelper;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_online_auido, container, false);
        ButterKnife.bind(this, view);

        initRecycle();
        mHelper = new PermissionHelper(this);
        if (!mHelper.hasPermissions(this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
            mHelper.requestPermissions("请授予环球少年文件获取权限！",
                    new PermissionHelper.PermissionListener() {
                        @Override
                        public void doAfterGrand(String... permission) {
                            getListData();
                        }

                        @Override
                        public void doAfterDenied(final String... permission) {
                            LogUtil.MyLog("mHelper", "========拒绝=======" + permission.toString());
                            mHelper.showMessageOKCancel(getResources().getString(R.string.recode_permission), new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    mHelper.executePermissionsRequest(getActivity(), new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, mHelper.REQUEST_PERMISSION_CODE);
                                }
                            });
                        }
                    }, Manifest.permission.READ_EXTERNAL_STORAGE);
        } else {
            getListData();
        }

        return view;
    }

    private void initRecycle() {
        listData = new ArrayList<>();

        LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(manager);

        listAdapter = new FragmentLoactionAudioAdapter(getActivity(), listData);
        recyclerView.setAdapter(listAdapter);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }


    private void getListData() {
        //获取本地数据库中的 录音资源
//        ArrayList<AudioBean> dbData = RecorderAudioDBManager.getInstance(getActivity()).getAudioBookList(LoginUserSharePrefernce.getCustomId());
        ArrayList<AudioBean> dbData = RecorderAudioDBManager.getInstance(getActivity(),Constant.SHOWRECOR_TABLENAME).getAudioBookList(Constant.TABLEID); //查询本地

        //获取本地媒体库中的资源
        ArrayList<AudioBean> localData = Utils.getLoctionAudio();

        for (int i = 0; i < dbData.size(); i++) {
            for (int j = 0; j < localData.size(); j++) {

                boolean isDelete = true;
                AudioBean loaclAudio = localData.get(j);
                AudioBean dbAudio = dbData.get(i);
                //  for循环判断本地中是否含有数据库中某一条AudioBean
                if (dbAudio.getPlayLink().equals(loaclAudio.getPlayLink())) {
                    dbAudio.setRDurationFormat(DataUtil.formatPlayTime((long) (loaclAudio.getResourceDuration() * 1000)));
                    dbAudio.setCoverImg(dbAudio.getCoverImg());
                    listData.add(dbAudio);
                    break;
                }

                if (isDelete && j == localData.size() - 1) {
                    RecorderAudioDBManager.getInstance(getActivity(),Constant.SHOWRECOR_TABLENAME).deleteAudioBook(dbAudio.getPlayLink());
                }
            }
        }

        listAdapter.notifyDataSetChanged();
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
//        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        mHelper.handleRequestPermissionsResult(requestCode, permissions, grantResults);
    }
}